package com.atguigu.gmall.order.Listener.mq;

import com.atguigu.gmall.common.constants.RabbitMqConst;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.to.ware.WareStockStatusTo;
import com.atguigu.gmall.order.service.OrderService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/10/18 1:19
 */
@Slf4j
@Service
public class OrderStockListener {
    @Autowired
    OrderService orderService;

    //根据库存结果修改状态
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitMqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false",exclusive = "false"),
            exchange = @Exchange(value = RabbitMqConst.EXCHANGE_DIRECT_WARE_ORDER,type ="direct",durable = "true",autoDelete = "false")
            ,key = RabbitMqConst.ROUTING_WARE_ORDER))
    public void updateStatusByStock(Message message, Channel channel){

        try {
            String str = new String(message.getBody());
            WareStockStatusTo wareStockStatusTo = JsonUtil.json2Obj(str, new TypeReference<WareStockStatusTo>() {
            });
            log.info("感知库存扣减结果:{}",wareStockStatusTo);
            Long orderId = wareStockStatusTo.getOrderId();
            String status = wareStockStatusTo.getStatus();
            ProcessStatus newProcessStatus=null;
            //状态： ‘DEDUCTED’  (已减库存) 状态：  ‘OUT_OF_STOCK’  (库存超卖)
            switch (status){
                case "DEDUCTED":
                    newProcessStatus=ProcessStatus.WAITING_DELEVER;
                    break;
                case "OUT_OF_STOCK":
                    newProcessStatus=ProcessStatus.STOCK_EXCEPTION;
                    break;
                default:
            }
            //修改状态
            orderService.updateStatusByStock(orderId,newProcessStatus);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("根据库存结果修改订单状态失败",e);
        }
    }
}
